<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="600px"
      :before-close="closeDialog"
    >
      <el-row style="margin-top: 24px">
        通过Excel表格批量创建销售账号，请根据模板填写销售信息
        <a :href="mubanUrl" style="color: #e6a23c">下载模板</a>
      </el-row>
      <input
        class="input-file"
        type="file"
        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        @change="exportData"
      />
      <el-button type="primary" size="small" @click="btnClick"
        >导入EXCEL<i class="el-icon-upload el-icon--right"></i>
      </el-button>
      <p style="color: red; margin-top: 12px">
        注意 : 仅能导入指定格式模板，模板点击上方下载模板按钮下载
      </p>
      <p v-if="isVisibleSuccess" class="import-success">导入完成</p>
      <el-form ref="formRef" label-position="left">
        <el-form-item label="" v-if="isVisiblePercentage">
          <div class="progress">
            <el-progress :percentage="percentage"></el-progress>
          </div>
        </el-form-item>
      </el-form>
      <p v-if="isVisibleSuccess" class="tips">
        共导入
        <span>{{ total }} </span>条，成功 <span>{{ successNum }} </span>条，失败
        <span>{{ failNum }} </span>条
        <el-button type="text" :style="{ color: 'red' }" @click="exportFailData"
          >导出失败数据</el-button
        >
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="closeDialog"
          size="small"
          :loading="loading"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from "xlsx";
import generateExcel from "@/utils/generateExcel.js";
import { reqImportData } from "@/api/modules/distribute";
export default {
  name: "importScoreDialog",
  props: {
    mubanUrl: {
      type: String,
      default: "",
    },
    importUrl: {
      type: String,
      default: "",
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      visible: false,
      loading: false,
      progress: 0,
      showCancel: true,
      successNum: 0,
      failNum: 0,
      paramsArr: [],
      outdata: null,
      isVisibleSuccess: false,
      isVisiblePercentage: false,
      index: 0, // 上传顺序
      percentage: 0,
      total: "",
      importFailList: [["序号", "姓名", "手机号"]],
    };
  },
  watch: {
    index(successNum) {
      this.percentage = Math.ceil((successNum / this.total) * 100);
      if (successNum === this.total) {
        this.loading = false;
        this.isVisibleSuccess = true; // 显示成功
        this.$message.success("全部处理完成");
      }
    },
  },
  methods: {
    init() {
      this.visible = true;
    },
    closeDialog() {
      this.visible = false;
    },

    /**
     * 初始化保存失败列表的变量，保存下表头信息
     */
    initFailList() {
      this.importFailList = [["序号", "姓名", "手机号"]];
    },
    /**
     * 点击导出失败数据时触发
     */
    exportFailData() {
      generateExcel(this.importFailList, "失败数据.xlsx");
      this.initFailList();
      this.closeDialog();
    },
    btnClick() {
      this.initFailList();
      this.isVisiblePercentage = false;
      this.isVisibleSuccess = false;
      this.index = 0;
      this.failNum = 0;
      this.successNum = 0;
      this.percentage = 0;
      document.querySelector(".input-file").value = "";
      document.querySelector(".input-file").click();
    },
    exportData(event) {
      if (!event.currentTarget.files.length) {
        return;
      }
      const _this = this;
      // 拿取文件对象
      var f = event.currentTarget.files[0];
      // 用FileReader来读取
      var reader = new FileReader();
      // 重写FileReader上的readAsBinaryString方法
      FileReader.prototype.readAsBinaryString = function(f) {
        // debugger
        var binary = "";
        var wb; // 读取完成的数据
        var outdata; // 你需要的数据
        var reader = new FileReader();
        reader.onload = function(e) {
          // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          // 接下来就是xlsx了，具体可看api
          wb = XLSX.read(binary, {
            type: "binary",
          });
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          _this.$message({
            type: "success",
            message: "快速导入中...",
          });
          _this.outdata = outdata; // 获取数据
          // 自定义方法向父组件传递数据
          _this.onSubmit(); // 调用导入接口
        };
        reader.readAsArrayBuffer(f);
      };
      reader.readAsBinaryString(f);
    },
    // 提交
    onSubmit() {
      if (!this.outdata.length) {
        this.$message.warning("上传的excel文件格暂无数据");
      }
      if (
        !this.outdata[0]["序号"] ||
        !this.outdata[0]["姓名"] ||
        !this.outdata[0]["手机号"]
      ) {
        this.$message.warning("上传的excel文件格式必须和模板保持一致！");
        return;
      }
      this.isVisiblePercentage = true;
      this.outdata.forEach((item) => {
        this.paramsArr.push({
          salesName: item["姓名"],
          mobile: item["手机号"],
          moduleType: "OCCUPATION_MODULE_TYPE",
        });
      });
      this.total = this.paramsArr.length;
      this.importData(this.paramsArr);
    },
    importData(data) {
      this.loading = true;
      this.index++;
      reqImportData(
        {
          ...data[this.index - 1],
        },
        this.importUrl
      )
        .then((res) => {
          if (res.code == 200) {
            this.successNum++;
          } else {
            this.failNum++;
            this.importFailList.push([
              this.index,
              data[this.index - 1].salesName,
              data[this.index - 1].mobile,
              data[this.index - 1].moduleType,
              res.status_desc,
            ]);
          }
        })
        .catch((err) => {
          let tempErr;
          if (typeof err === "string") {
            tempErr = err;
          }
          if (typeof err === "object") {
            tempErr = err.message || err.status_desc || "未知原因";
          }
          this.importFailList.push([
            this.index,
            data[this.index - 1].mobile,
            data[this.index - 1].stageName,
            data[this.index - 1].score,
          ]);
          this.failNum++;
        })
        .finally(() => {
          if (this.index < this.paramsArr.length) {
            this.importData(data);
          } else {
            this.paramsArr = [];
            this.$emit("upload-success");
            this.$message.success(
              `处理完成，共处理${this.paramsArr.length}个请求,成功${this.successNum}个，失败${this.failNum}个`
            );
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding-top: 0 !important;
  position: relative;
}
.input-file {
  display: none;
}

.top {
  margin-bottom: 15px;
  line-height: 24px;
}
.progress {
  margin-top: 11px;
}

.link {
  color: #409eff;
  cursor: pointer;
}

.import-success {
  margin-top: 12px;
  color: #0ab469;
}
.el-form-item {
  margin-bottom: 0;
}
.tips {
  font-size: 13px;
  // color: rgb(240, 44, 44);
  span {
    color: #f9a100;
  }
}

.warning {
  background-color: #fffbe6;
  margin-bottom: 24px;
  padding: 12px 18px;
  margin: 0 -24px 24px -24px;
  > span {
    padding-left: 8px;
    color: #595959;
  }
}
</style>
